package com.levy.utils.jvisualVM;

/**
 * Created by levy on 2019/6/27.
 */
public class ThreadDemo1 {
    public static void main(String[] args) {
        long l = System.nanoTime();
        Station station = new Station();
        for (int i = 0; i < 1; i++) {
            TicketThread ticketThread1 = new TicketThread(station);
            Thread t1 = new Thread(ticketThread1);
            t1.start();
        }
        System.out.println(System.nanoTime() - l);
    }
}

class Station {
    //记录车票的数量   使用static目的：确保2个窗口是共同在出售这20张票而不是这2个窗口各自出售20张 共出售40张
    private static int tickets = 10000;

    //定义一个买票的方法
    public void getTicket() {
        synchronized (this) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "买走1张，车票还剩: " + (--tickets) + "张 ！");
            } else {
                TicketThread.over = true;
            }
        }
    }
}

class TicketThread implements Runnable {
    private Station station;
    public static volatile boolean over = false;

    public TicketThread(Station station) {
        this.station = station;
    }

    @Override
    public void run() {
        while (!over) {
            station.getTicket();
        }
        System.out.println("all over");
    }
}
